import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { loginOut } from "@/apis/index.js";
// import { Local } from "@/utils/storage.js";
// import Cookies from "js-cookie";

// 定义常量
const CONTENT_TYPE = "multipart/form-data; boundary=XXX";
const LOGIN_STATUS_KEY = "loginStatus";
const ONE_DAY_MS = 1000 * 60 * 60 * 24;
const TWO_HOURS_MS = 2 * 60 * 60 * 1000;

// 创建axios实例
export const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // api的base_url
  timeout: 9999999999, // 请求超时时间
  // timeout: 5000, // 请求超时时间
  withCredentials: true,
});

request.defaults.headers.post["Content-Type"] = CONTENT_TYPE;

// 请求拦截器
request.interceptors.request.use(
  async (config) => {
    return config;
  },
  (error) => {
    console.log("请求拦截器", error);
    Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // const isCode =
    //   Number(response.data.code) === 0 && Number(response.data.code) === -1;
    // const isMsg = response.data.mmsg || response.data.msg;
    // if (isCode && isMsg) {
    //   ElMessage({
    //     message: response.data.message || response.data.msg,
    //     grouping: true,
    //     offset: window.screen.height / 3,
    //     customClass: "bai-message",
    //     type: "warning",
    //   });
    // }
    const code = response.data.code || response.data.mcode;
    // 对响应错误做处理
    switch (Number(code)) {
      case -2:
        ElMessageBox.alert("已退出登录，请重新登录。", "登录已过期", {
          confirmButtonText: "确认",
          callback: async (action) => {
            await clearLocalStorage();
          },
        });
        break;
      case 200:
        localStorage.removeItem("isLogin");
        localStorage.removeItem("userInfo");
        break;
      default:
    }
    return response;
  },
  (error) => {
    ElMessageBox.alert("已退出登录，请重新登录。", "登录已过期", {
      confirmButtonText: "确认",
      callback: async (action) => {
        await clearLocalStorage();
      },
    });
    return Promise.reject(error);
  },
);

/**
 * 封装请求数据FormData格式:
 * 在这里实现的FormData封装，以便传给后端
 * @param {*} obj
 */
function getFormData(obj = {}) {
  const formData = new FormData();
  Object.keys(obj).forEach((key) => {
    formData.append(key, obj[key]);
  });
  return formData;
}

//清空本地存储
export async function clearLocalStorage() {
  localStorage.removeItem("isLogin");
  localStorage.removeItem("userInfo");
  await loginOut();
  window.location.reload();
}
